﻿using System;
using System.Reflection;
using Unity.Interception.PolicyInjection.Pipeline;

namespace pri.smilly.QuickStart.Aop {
    public class CallHandler : ICallHandler {
        public int Order { get; set; }
        public MethodInfo BeforeHandle { set; private get; }
        public MethodInfo AfterHandle { set; private get; }
        public MethodInfo ExceptHandle { set; private get; }
        public MethodInfo FinallyHandle { set; private get; }

        public CallHandler(int order) {
            Order = order;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) {
            BeforeHandle?.Invoke(Activator.CreateInstance(BeforeHandle.DeclaringType), new object[] { input });
            IMethodReturn result = getNext().Invoke(input, getNext);
            if (null != result.Exception)
                ExceptHandle?.Invoke(Activator.CreateInstance(ExceptHandle.DeclaringType), new object[] { input, result.Exception });
            else
                AfterHandle?.Invoke(Activator.CreateInstance(AfterHandle.DeclaringType), new object[] { input, result });

            FinallyHandle?.Invoke(Activator.CreateInstance(FinallyHandle.DeclaringType), new object[] { input });
            return result;
        }
    }
}
